package com.company.thread;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description: 同步机制之 ： veresion1: synchronized-wait-notify    version2: lock-await-signal   version3: blcokingqueue-atom*-信号量
 * @author: ruoan
 * @date: 2020/12/12 8:58
 */
public class SyncVersion1 {

    public static void main(String[] args) {

        MyResource1 myResource1 = new MyResource1();
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                try {
                    myResource1.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }, String.valueOf(i)).start();
        }
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                try {
                    myResource1.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }, String.valueOf(i)).start();
        }

    }
}

@Slf4j
class MyResource1 {

    private int num = 0;

    /**
     * 加1方法
     */
    public synchronized void increment() throws InterruptedException {
        // 当num==1时候，进入循环体，否则执行+1
        while (num != 0) {
            this.wait();
        }
        num++;
        log.info(Thread.currentThread().getName() + "\t increment()");
        this.notifyAll();


    }
    /**
     * 减1方法
     */
    public synchronized void decrement() throws InterruptedException {
        // 当num==0时候，进入循环体,否则执行-1
        while (num == 0) {
            this.wait();
        }
        num--;
        log.info(Thread.currentThread().getName() + "\t decrement()");
        this.notifyAll();

    }

}